package com.alibaba.citrus.cr.order.open.api.facade.service;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.lock.RedisLock;
import com.alibaba.citrus.cr.order.open.api.facade.common.model.ShippingOrderCreatedMessage;
import com.alibaba.citrus.cr.order.open.api.facade.common.model.ShippingOrderCreatedMessageData;
import com.alibaba.citrus.cr.order.open.api.facade.common.model.ShippingOrderCreatedMessageDataLine;
import com.alibaba.citrus.cr.order.open.api.facade.transfer.CreateFulfillmentOrderReqFactory;
import com.alibaba.citrus.cr.unified.inventory.handler.FulfillmentOrderOpenApi;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.CreateFulfillmentOrderReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.UpdateFulfillmentOrderFeaturesReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.response.fulfillment.FulfillmentOrderResponse;
import com.alibaba.cloud.retail.delivery.api.service.bcfulfillment.FulfillmentOrderAbilityService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.mninventorycenter.deliverymessageprocess.dto.ReceiveShippingOrderCreatedMessageRequest;
import com.epoch.app.mninventorycenter.deliverymessageprocess.service.DeliveryMessageProcessService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * @description:注释
 * @author: yuhw
 * @date: 2024年01月07日 14:24
 **/
@Service
@Primary
public class DeliveryMessageProcessServiceImpl implements DeliveryMessageProcessService {
    private static Log log = Log.getLogger(DeliveryMessageProcessServiceImpl.class);

    private static final String IS_ALLOCATE = "1";
    @DubboReference
    private FulfillmentOrderAbilityService fulfillmentOrderAbilityService;
    @Resource
    private FulfillmentOrderOpenApi fulfillmentOrderOpenApi;
    @Resource
    private CreateFulfillmentOrderReqFactory createFulfillmentOrderReqFactory;

    @Override
    @FacadeInvoker(remark = "接收装运单消息")
    public Result<String> receiveShippingOrderCreatedMessage(ReceiveShippingOrderCreatedMessageRequest receiveRequest) {
        log.info("receiveShippingOrderCreatedMessage_request:{}", JSON.toJSONString(receiveRequest));
        //判断下是否需要接收
        boolean acceptable = accept(receiveRequest);
        if (!acceptable){
            log.info("receiveShippingOrderCreatedMessage_not_accept:{}",JSON.toJSONString(receiveRequest));
            return Result.success("no need to process message");
        }
        ShippingOrderCreatedMessage createdMessage = JSON.parseObject(receiveRequest.getMessage(), ShippingOrderCreatedMessage.class);
        try (RedisLock lock = new RedisLock(BcOrderConstants.REDIS_CACHE_CODE(), "receiveShippingOrderCreated" + createdMessage.getData().getOrderNo(), 60000, 120000)) {
            if (!lock.lock()) {
                return Result.fail("", "不能重复提交");
            }
            //查询出调拨单
            List<CreateFulfillmentOrderReq> reqList = createFulfillmentOrderReqFactory.batchBuild(createdMessage.getData());
            log.info("batchBuild_result:{}", JSON.toJSONString(reqList));
            if (CollectionUtils.isEmpty(reqList)) {
                throw new FacadeException("OTS-03-005-00-15-201");
            }
            reqList.forEach(req -> {
//            CreateFulfillmentOrderReq req = createFulfillmentOrderReqFactory.build(createdMessage);
                //调用履约
                log.info("createReverseOrder_request:{}", JSON.toJSONString(req));
                if (Objects.isNull(req) || CollectionUtils.isEmpty(req.getDetailList())) {
                    throw new FacadeException("OTS-03-005-00-15-201");
                }
                com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<FulfillmentOrderResponse> reverseOrder = fulfillmentOrderOpenApi.createReverseOrder(req);
                log.info("createReverseOrder_result:{}", JSON.toJSONString(reverseOrder));
                if (reverseOrder != null && reverseOrder.isSuccess()) {
                    UpdateFulfillmentOrderFeaturesReq featuresReq = createFulfillmentOrderReqFactory.build(req, reverseOrder.getResult());
                    log.info("PlanTransferFulfillmentHandler_updateFulfillmentOrderFeatures_request:{}",JSON.toJSONString(featuresReq));
                    com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result featureRes = fulfillmentOrderAbilityService.updateFulfillmentOrderFeatures(featuresReq);
                    log.info("PlanTransferFulfillmentHandler_updateFulfillmentOrderFeatures_result:{}",JSON.toJSONString(featureRes));
                }
//            String fulfillmentOrderNo = Optional.ofNullable(reverseOrder).map(com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result::getResult)
//                    .map(FulfillmentOrderResponse::getFulfillmentOrderNo).orElse(UUID.randomUUID().toString().replace("-", ""));
            });

            return Result.success(System.currentTimeMillis() + "");
        }catch (Throwable e){
            if (e instanceof FacadeException){
                FacadeException ex = (FacadeException) e;
                if ("OTS-03-005-00-15-240".equals(ex.getErrorCode())){
                    return Result.success(System.currentTimeMillis() +"");
                }
            }
            if (e instanceof FacadeException){
                FacadeException ex = (FacadeException) e;
                if ("OTS-03-005-00-15-241".equals(ex.getErrorCode())){
                    return Result.success(System.currentTimeMillis() + "");
                }
            }
            if (e instanceof FacadeException){
                FacadeException ex = (FacadeException) e;
                if ("OTS-03-005-00-15-256".equals(ex.getErrorCode())){
                    return Result.success(System.currentTimeMillis() + "");
                }
            }
            throw e;
        }
    }

    private boolean accept(ReceiveShippingOrderCreatedMessageRequest receiveRequest){
        if (receiveRequest == null){
            return false;
        }
        ShippingOrderCreatedMessage createdMessage =JSON.parseObject(receiveRequest.getMessage(), ShippingOrderCreatedMessage.class);
        log.info("accept_message:{}",JSON.toJSONString(createdMessage));
        List<ShippingOrderCreatedMessageDataLine> messageDataLines = Optional.ofNullable(createdMessage).map(ShippingOrderCreatedMessage::getData)
                .map(ShippingOrderCreatedMessageData::getOrderLine)
                .orElse(Lists.newArrayList());
        return messageDataLines.stream().anyMatch(line -> IS_ALLOCATE.equals(line.getIsAllocate()));
//        JSONObject msg = JSON.parseObject(receiveRequest.getMessage());
//        if (Objects.isNull(msg) || msg.getJSONObject("data") == null){
//            return false;
//        }
//
//        ShippingOrderCreatedMessage createdMessage = JSON.parseObject(JSON.toJSONString(msg.getJSONObject("data")),ShippingOrderCreatedMessage.class);
//        log.info("createdMessage:{}",JSON.toJSONString(createdMessage));
//        //判断是否接受处理消息
//        if (createdMessage == null || CollectionUtils.isEmpty(createdMessage.getOrderLine())){
//            return false;
//        }
//        //TODO 判断是否接受消息的方式 可能还需要改动
//        return createdMessage.getOrderLine().stream().anyMatch(detailMessage -> IS_ALLOCATE.equals(detailMessage.getIsAllocate()));
    }
}
